package com.wteam.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wteam.PoJo.DTO.cart;
import com.wteam.PoJo.DTO.goods;
import com.wteam.PoJo.DTO.memberdto;
import com.wteam.PoJo.DTO.region;
import com.wteam.PoJo.VO.OrderGoodVo;
import com.wteam.PoJo.VO.changegoods;
import com.wteam.PoJo.VO.ordervo;
import com.wteam.config.JWT.jwt;
import com.wteam.exception.orderException;
import com.wteam.mapper.*;
import com.wteam.service.GoodsCartServicer;
import com.wteam.untils.MemberIdAndName;
import com.wteam.untils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class GoodsCartServiceimpl implements GoodsCartServicer {
    @Autowired
    private Goodsmapper goodsmapper;
    @Autowired
    private HttpServletRequest httpServletRequest;
    @Autowired
    private MemberIdAndName memberIdAndName;
    @Autowired
    private Memberdtomapper memberdtomapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private RegionMapper regionMapper;

    @Autowired
    private GoodsCartmapper goodsCartmapper;

    @Override
    public Result addcart(Integer goodid) {
        Map<String, Object> claims = jwt.parseJWT(httpServletRequest.getHeader("token"));
        Integer memberId = (Integer) claims.get("id");

        //判断购物车是不是有该商品，有加1
        LambdaQueryWrapper<cart> qw = new LambdaQueryWrapper();
        qw.eq(cart::getMemberId, memberId)
                .eq(cart::getGoodsId, goodid);
        Long aLong = goodsCartmapper.selectCount(qw);

        if (aLong != 0) {
            cart cart = goodsCartmapper.selectOne(qw);
            cart.setQuantity(cart.getQuantity() + 1);
            goodsCartmapper.update(cart, qw);
            return Result.success("购物添加成功");
        }
        cart goodscart = new cart();
        goodscart.setGoodsId(goodid);
        goodscart.setMemberId(memberId);
        goodscart.setAddedTime(LocalDateTime.now());
        goodsCartmapper.insert(goodscart);

        return Result.success("购物添加成功");
    }

    @Override
    public Result listcar(Integer page, Integer pagesize) {
        Map<String, Object> claims = jwt.parseJWT(httpServletRequest.getHeader("token"));
        Integer memberId = (Integer) claims.get("id");

        IPage<cart> iPage = new Page<>(page, pagesize);
        LambdaQueryWrapper<cart> qw = new LambdaQueryWrapper();
        qw.eq(cart::getMemberId, memberId);
        IPage<cart> iPage1 = goodsCartmapper.selectPage(iPage, qw);
        List<cart> records = iPage1.getRecords();
        for (cart record : records) {
            //根据商品id查详细的商品详细
            goods goods = goodsmapper.selectById(record.getGoodsId());
            record.setGoodimage(goods.getSmall());
            record.setGoodname(goods.getGoodsName());
            record.setOneGoodPrice(goods.getPrice());
            record.setIntro(goods.getIntro());
        }

        return Result.success(records);
    }

    @Override
    public Result deletegoodId(List<Integer> goodid) {
        Map<String, Object> claims = jwt.parseJWT(httpServletRequest.getHeader("token"));
        Integer memberId = (Integer) claims.get("id");
        if (goodid.size() == 0 || goodid.isEmpty() || goodid == null) {
            throw new orderException("，传id");
        }

        for (Integer integer : goodid) {
            LambdaQueryWrapper<cart> qw = new LambdaQueryWrapper();
            qw.eq(cart::getMemberId, memberId).eq(cart::getGoodsId, integer);
            goodsCartmapper.delete(qw);
        }

        return Result.success("商品成功被删除");
    }

    @Override
    public Result sumcart(List<changegoods> changegoods) {
        List<cart> carts = new ArrayList<>();
        Integer memberid = memberIdAndName.Memberid(httpServletRequest.getHeader("token"));
        for (com.wteam.PoJo.VO.changegoods changegood : changegoods) {
            cart cart = new cart();
            BeanUtils.copyProperties(changegood, cart);
//            cart.setMemberId(memberid);
            carts.add(cart);

        }

        for (cart cart : carts) {
            LambdaQueryWrapper<cart> cartLambdaQueryWrapper = new LambdaQueryWrapper<>();
            cartLambdaQueryWrapper.eq(com.wteam.PoJo.DTO.cart::getMemberId, memberid)
                    .eq(com.wteam.PoJo.DTO.cart::getGoodsId, cart.getGoodsId());
            goodsCartmapper.update(cart, cartLambdaQueryWrapper);
        }
        //计算价格

        LambdaQueryWrapper<cart> qw = new LambdaQueryWrapper();
        qw.eq(cart::getMemberId, memberid)
                .eq(cart::getSelected, 1);
        //我选中的购物车
        List<cart> carts1 = goodsCartmapper.selectList(qw);
        log.info(carts1.toString());


        Double sum = 0.0;
        for (cart cart : carts1) {
            //查看金额
            LambdaQueryWrapper<goods> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(goods::getId, cart.getGoodsId());
            goods goods = goodsmapper.selectOne(lambdaQueryWrapper);
            log.info(goods.getPrice().toString());
            log.info(cart.getQuantity().toString());
            double v = goods.getPrice() * cart.getQuantity();
            sum += v;
        }

        return Result.success("sum:" + sum);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result buycart() {
        ordervo order = new ordervo();
        Integer memberid = memberIdAndName.Memberid(httpServletRequest.getHeader("token"));
        String membername = memberIdAndName.username(httpServletRequest.getHeader("token"));

        memberdto memberdto = memberdtomapper.selectById(memberid);
        order.setMemberId(memberid);
        order.setMemberName(membername);

        //用默认地址代替收货地址
        LambdaQueryWrapper<region> qw = new LambdaQueryWrapper();
        qw.eq(region::getMemberId, memberid)
                .eq(region::getId, memberdto.getRegionId());
        //用户默认的收货地址
        region region = regionMapper.selectOne(qw);
        if (region == null) {
            throw new orderException("先去设置默认地址");
        }
        log.info(region.toString());
        //省份城市
        //存在order里
        order.setConsignee_address_id_path(region.getId());
        order.setProvince(region.getProvince());
        order.setUrban(region.getUrban());
        order.setFulladdress(region.getFullAddress());
        order.setConsigneeMobile(region.getTelephone());
        order.setConsigneeName(region.getConsignee());

        //设置商品详情（根据用户id和选中未1,查商品id）
        LambdaQueryWrapper<cart> Cartqw = new LambdaQueryWrapper<>();
        Cartqw.eq(cart::getMemberId, memberid)
                .eq(cart::getSelected, 1);
        //购物车全部商品
        List<cart> carts = goodsCartmapper.selectList(Cartqw);
        List<OrderGoodVo> list = new ArrayList<>();
        //遍历商品，将商品单价，数量，图片，名字存起来
        for (cart cart : carts) {
            //根据商品id查商品详情
            goods goods = goodsmapper.selectById(cart.getGoodsId());
            log.info(goods.toString());
            OrderGoodVo orderGoodVo = new OrderGoodVo();
            orderGoodVo.setGoodId(goods.getId());
            orderGoodVo.setGoodname(goods.getGoodsName());
            orderGoodVo.setGoodtype(goods.getGoodsType());
            orderGoodVo.setGoodphoto(goods.getSmall());
            orderGoodVo.setGoodnumber(cart.getQuantity());
            orderGoodVo.setGoodprice(goods.getPrice());
            list.add(orderGoodVo);
        }
        order.setCarts(list);
        return Result.success(order);
    }


}
